import {ChangeDetectorRef, Component, ElementRef, OnInit} from '@angular/core';
import {MusicService, Song} from '../server/music.service';
import {tryCatch} from 'rxjs/internal/util/tryCatch';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-music',
  templateUrl: './music.component.html',
  styleUrls: ['./music.component.css']
})
export class MusicComponent implements OnInit {
  /*控制是否显示音乐控制*/
  public isShowControl = false;
  /*控制音乐列表控制*/
  public isShowMusicList = false;
  /*控制音乐按钮*/
  public isPause = false;
  /*音乐列表*/
  public listMusic;
  /*音乐资源url信息*/
  public urlData = null;
  /*音乐资源*/
  public urlMusic = '';
  /*登录标志*/
  public login = null;
  /*audio*/
  public audio = null;
  /*媒体对象*/
  public audioObj: Song;
  /*当前的列表的序列*/
  public currentMedia = {
    id: 0,
    index: 0
  };
  public timer: any; // 定时器
  public MediaTime = {duration: '00:00', currentTime: '00:00'};
  public progressWidth = 0;
  constructor(private musicServer: MusicService, private el: ElementRef,
              private changeDetectorRef: ChangeDetectorRef, private cook: CookieService) {
  }

  ngOnInit() {
    /*初始化audio对象*/
    this._initAudio('audio');
  }
  /*初始化音乐播放对象
   * audioId: audio元素 的id
  */
  public _initAudio(audioId: string) {
    const loginFlag = sessionStorage.getItem('login');
    this.audio = document.getElementById(audioId);
    /*进行用户的登录的操作*/
    /*this.musicServer.loginMusic()
      .subscribe(res => {
        this.cook.set('res' , res.status , this.musicServer.setCookie(30));
        console.log(this.cook.get('res'));
      }, error => {
        console.log(error);
      });*/
    /*进行数据的额操作*/
    this.musicServer.acquireMusicList()
      .subscribe(res => {
        /*初始胡音乐资源列表*/
        this.listMusic = res.result;
        /*初始化音乐资源*/
        this.takeUrlMusic(this.listMusic[0].id);
        this.currentMedia = {
          id: this.listMusic[0].id,
          index: 0
        };
        this.isPause = false;
        /*初始化Song对象*/
        this.audioObj = new Song(this.listMusic[0].id, this.listMusic[0].name,
          this.listMusic[0].song.album.name, this.listMusic[0].song.album.picUrl);
      } );
  }
  /**
   * 获取歌曲时长
   * @param Media
   */
  public getTime(Media: HTMLAudioElement, pause?: string) {
    const _this = this;
    setTimeout(function () {
      let duration = Media.duration;
      if (isNaN(duration)) {
        _this.getTime(Media);
      } else {
        duration = Math.round(Media.duration);
        _this.MediaTime.duration = _this.setTimes(duration);
        console.log('该歌曲的总时间为：' + _this.setTimes(duration) + '秒');
        if (pause !== 'pause') {
          _this.clearTimes();
        }

        _this.timer = setInterval(() => {
          _this.MediaTime.currentTime = _this.setTimes(Math.floor(Media.currentTime));
          // console.log('currentTime：',_this.setTimes(Math.floor(Media.currentTime)));
          _this.progressWidth += (100 / duration);
          if (_this.audio.paused) {
            //noinspection TypeScriptUnresolvedFunction
            clearInterval(_this.timer);
            _this.isPause = false;
          }
          if (_this.MediaTime.currentTime >= _this.MediaTime.duration || _this.audio.ended) {
            console.log('结束播放');
            _this.isPause = false;
            _this.forwardMusic();
            //noinspection TypeScriptUnresolvedFunction
            clearInterval(_this.timer);
          }
        }, 1000);
      }
    }, 10);
  }
  /*播放音乐
   * @params: url: 音乐的资源的链接
  */
  public playMedia(url: string, index: any) {
      const _this = this;
    _this.audio.pause();
    _this.audioObj = null;
    _this.audio.src = url;
    _this.audio.load();
    _this.audioObj = new Song( _this.listMusic[index].id, _this.listMusic[index].name,
      _this.listMusic[index].song.album.name, _this.listMusic[index].song.album.picUrl);
      try {
        // 延时执行函数的作用，
        setTimeout(function () {
          _this.audio.play();
          _this.getTime(_this.audio);
        }, 10);
      } catch {
        setTimeout(function () {
          _this.audio.play();
          _this.getTime(_this.audio);
        }, 10);
      }
  }
  /*
   *上一首音乐
  */
  public backwardMusic(): void {
    const _this = this;
    /*_this.isPause = true;*/
    if (_this.currentMedia.index === 0) {
      console.log('第一首');
      _this.currentMedia = {
        id: _this.listMusic[_this.listMusic.length - 1].id,
        index: _this.listMusic.length - 1
      };
    } else {
      console.log('不是第一首', _this.currentMedia);
      _this.currentMedia = {
        id: _this.listMusic[_this.currentMedia.index - 1].id,
        index: _this.currentMedia.index - 1
      };
    }
    console.log(_this.currentMedia);
    /*重新加载音乐的资源的链接*/
    _this.takeUrlMusic(Number(_this.currentMedia.id));
    _this.playMedia(_this.urlMusic, _this.currentMedia.index);

  }
  /*
   *播放暂停音乐
   */
  public playMusic(): void {
    const _this = this;
    /*控制播放字体图标*/
    if ( _this.audio.paused) {
      _this.isPause = true;
      _this.audio.play();
      _this.getTime(_this.audio, 'pause');
    } else {
      _this.isPause = false;
      _this.audio.pause();
    }
  }
  /*
   *下一首音乐
  */
  public forwardMusic(): void {
    const _this = this;
    if (_this.currentMedia.index >= _this.listMusic.length - 1 ) {
      console.log('最后一首');
      _this.currentMedia = {
        id: this.listMusic[0].id,
        index: 0
      };
    } else {
      _this.currentMedia = {
        id: _this.listMusic[_this.currentMedia.index + 1].id,
        index: _this.currentMedia.index + 1
      };
    }
    console.log(_this.currentMedia);
    /*重新加载音乐的资源的链接*/
    _this.takeUrlMusic(Number(_this.currentMedia.id));
    _this.playMedia(_this.urlMusic, _this.currentMedia.index);
  }
  /*从音乐列表中播放音乐*/
  public listOneMusic(id: number, index: number, $event): void {
    const _this = this;
    /*暂停播放时的问题*/
    _this.currentMedia = {
      id: id,
      index: index
    };
    console.log(_this.currentMedia);
    /*更新音乐的资源*/
    _this.takeUrlMusic(id);
    _this.playMedia(_this.urlMusic, _this.currentMedia.index);
    /*处理当前的播放的列表的样式*/
    /*$event.target['style'].color = 'red';*/
  }

  /*获取音乐资源
    * @param: id 歌曲的id
  */
  public takeUrlMusic(id: number) {
    const _this = this;
    /*根据歌曲的id获取相应歌曲的数组的信息*/
    const url = _this.listMusic.find(item => {
      return item.id === id;
    });
    _this.urlData = url;
    _this.isPause = true;
    console.log(_this.urlData);
    /*获取相应歌曲的url*/
    _this.musicServer.takeUrlMusic(url.id)
      .subscribe(res =>  {
        _this.urlMusic = res.data[0].url;
    });
  }
  /**
   * 秒长转换分钟格式
   * @param duration
   * @returns {string}
   */
  public setTimes(duration) {
    let min, sec;
    min = Math.floor(duration / 60) < 10 ? ('0' + Math.floor(duration / 60)) : Math.floor(duration / 60);
    sec = Math.floor(duration - min * 60) < 10 ? ('0' + Math.floor(duration - min * 60)) : Math.floor(duration - min * 60 );
    return `${min}:${sec}`;
    // console.log(`${min}:${sec}`);
  }
  /*
   * 歌曲清除时长和定时器
   */
  public clearTimes() {
    const _this = this;
    _this.progressWidth = 0;
    clearInterval(_this.timer);
    _this.MediaTime.currentTime = '00:00';
  }
  /*刷新音乐的列表*/
  public newMusicList() {

  }
}
